<?php

namespace backend\modules\categories\models;

use Yii;
use yii\helpers\Inflector;
use common\components\Tree;

/**
 * This is the model class for table "{{%categories}}".
 *
 * @property int $id
 * @property int $parent_id
 * @property int $lft
 * @property int $rgt
 * @property int $level
 * @property string $path
 * @property string $extension
 * @property string $title
 * @property string $alias
 * @property string $note
 * @property string $description
 * @property int $published
 * @property string $params
 * @property string $metadesc
 * @property string $metakey
 * @property string $metadata
 * @property int $created_by
 * @property int $created_at
 * @property int $modified_by
 * @property int $modified_at
 * @property int $hits
 * @property string $language
 */
class Categories extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%categories}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['parent_id', 'published', 'created_by', 'created_at', 'modified_by', 'modified_at', 'hits'], 'integer'],
            [['title'], 'required'],
            [['description'], 'string'],
            [['alias'], 'string', 'max' => 400],
            [['extension'], 'string', 'max' => 50],
            [['title', 'note'], 'string', 'max' => 255],
            [['metadesc', 'metakey'], 'string', 'max' => 1024],
            [['language'], 'string', 'max' => 7],
            [['params', 'metadata'], 'filter', 'filter' => function ($value) {
                return is_array($value) ? json_encode($value) : $value;
            }],
            [['alias'], 'filter', 'filter' => function ($value) {
                return empty($value) ? Inflector::slug($this->title) : $value;
            }],
            [['level'], 'filter', 'filter' => function () {
                if ($this->parent_id) {
                    $parentModel = self::findOne($this->parent_id);
                    return $parentModel->level + 1;
                } else {
                    return 0;
                }
            }],
            [['created_at'], 'filter', 'filter' => function ($value) {
                return $value ?: ($this->getIsNewRecord() ? time() : $value);
            }],
            [['created_by'], 'filter', 'filter' => function ($value) {
                return $value ?: ($this->getIsNewRecord() ? Yii::$app->user->id : $value);
            }],
            [['modified_at'], 'filter', 'filter' => function () {
                return time();
            }],
            [['modified_by'], 'filter', 'filter' => function () {
                return Yii::$app->user->id;
            }],
            [['path'], 'filter', 'filter' => function () {
                if ($this->parent_id) {
                    $parentCategory = self::findOne($this->parent_id);
                    return $parentCategory->path . '/' . $this->alias;
                } else {
                    return $this->alias;
                }
            }]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('mod_categories', 'ID'),
            'parent_id' => Yii::t('mod_categories', 'FIELD_PARENT_ID_LABEL'),
            'path' => Yii::t('mod_categories', 'Path'),
            'extension' => Yii::t('mod_categories', 'Extension'),
            'title' => Yii::t('mod_categories', 'FIELD_TITLE_LABEL'),
            'alias' => Yii::t('mod_categories', 'FIELD_ALIAS_LABEL'),
            'note' => Yii::t('mod_categories', 'FIELD_NOTE_LABEL'),
            'description' => Yii::t('mod_categories', 'FIELD_DESCRIPTION_LABEL'),
            'published' => Yii::t('mod_categories', 'FIELD_PUBLISHED_LABEL'),
            'metadesc' => Yii::t('mod_categories', 'FIELD_METADESC_LABEL'),
            'metakey' => Yii::t('mod_categories', 'FIELD_METAKEY_LABEL'),
            'created_by' => Yii::t('mod_categories', 'FIELD_CREATED_BY_LABEL'),
            'created_at' => Yii::t('mod_categories', 'FIELD_CREATED_AT_LABEL'),
            'modified_by' => Yii::t('mod_categories', 'FIELD_Modified_By_LABEL'),
            'modified_at' => Yii::t('mod_categories', 'FIELD_Modified_At_LABEL'),
            'hits' => Yii::t('mod_categories', 'FIELD_HITS_LABEL'),
            'language' => Yii::t('mod_categories', 'FIELD_LANGUAGE_LABEL')
        ];
    }

    /**
     * 获取上级分类选择数组
     * @param string $extension
     * @param int $id
     * @return array
     */
    public function getParents($extension, $id = 0)
    {
        $categories = self::find()
            ->select(['id', 'parent_id', 'title', 'level', 'language'])
            ->where(['extension' => $extension, 'published' => 1]);
        if ($id > 0) {
            $categories->andWhere(['<>', 'id', $id]);
        }
        $tree = new Tree($categories->orderBy('lft')->asArray()->all());

        $items = $tree->makeTreeForHtml();

        $res = [];
        foreach ($items as $item) {
            $language = $item['language'] == '*' ? '' : ' (' . $item['language'] . ')';
            $prefix = str_repeat('- ', $item['level']);
            $res[$item['id']] = ($item['level'] > 0 ? ' ' : '') . $prefix . $item['title'] . $language;
        }

        return $res;
    }

    /**
     * 设置分类关系排序值
     * @param string $extension
     */
    public function setLftRgt($extension = 'mod_content')
    {
        $categories = self::find()
            ->select(['id', 'parent_id', 'level'])
            ->where('extension=:extension', [':extension' => $extension])
            ->orderBy('lft')
            ->asArray()->all();
        $tree = new Tree($categories);
        $newCategories = $tree->resetLftRgt();
        foreach ($newCategories as $newCategory) {
            $category = self::findOne($newCategory['id']);
            $category->lft = $newCategory['lft'];
            $category->rgt = $newCategory['rgt'];
            $category->save();
        }
    }

    /**
     * 分类列表
     * @param string $extension
     * @return array
     */
    public static function getList($extension)
    {
        $categories = self::find()
            ->select(['id', 'title', 'level', 'language'])
            ->where(['extension' => $extension, 'published' => 1])
            ->orderBy('lft')
            ->all();

        $list = [];
        foreach ($categories as $category) {
            $language = $category->language == '*' ? '' : ' (' . $category->language . ')';
            $prefix = str_repeat('- ', $category->level);
            $list[$category->id] = $prefix . $category->title . $language;
        }

        return $list;
    }
}
